import {
  Button,
  Col,
  Divider,
  Input,
  message,
  notification,
  Radio,
  RadioGroup,
  Row,
  Select,
  SelectOption,
  Space,
  Spin,
  Switch,
  Textarea
} from 'ant-design-vue'
import { computed, defineComponent, onMounted, ref } from 'vue'

import { couponApi, marketingApi } from '@/apis'
import UploadFile from '@/components/UploadFile'
import { useDialog } from '@/hooks'

import styles from './index.module.css'

export default defineComponent({
  name: 'SignInConfig',
  setup() {
    const loading = ref(false)
    const formModel = ref({
      dayPointOpen: false,
      dayCouponOpen: false,
      signContinueRewardOpen: false,
      assignDaysRewardOpen: false,
      assignDaysPointOpen: false,
      assignDaysCouponOpen: false,
      dayPointReward: '',
      couponId: '',
      signContinueReward: '',
      signContinueRewardInvalidDays: '',
      assignDays: '',
      assignDaysCouponId: '',
      assignDaysPointReward: '',
      signLinkType: 1,
      signImage: '',
      signWebUrl: '',
      signMiniappDirectory: '',
      signMiniappUrl: '',
      signPublicityCopy: ''
    })
    const resetData = ref({
      ...formModel.value
    })
    const couponOptions = ref<OptionItem[]>([])

    const pointDisabled = computed(() => !formModel.value.dayPointOpen)

    const couponDisabled = computed(() => !formModel.value.dayCouponOpen)

    const incrementDisabled = computed(
      () => !formModel.value.signContinueRewardOpen
    )

    const continuousDisabled = computed(
      () => !formModel.value.assignDaysRewardOpen
    )

    const subPointDisabled = computed(
      () => !formModel.value.assignDaysPointOpen
    )

    const subCouponDisabled = computed(
      () => !formModel.value.assignDaysCouponOpen
    )

    const { showConfirm } = useDialog()

    function validateDay() {
      if (formModel.value.dayPointOpen && formModel.value.dayCouponOpen) {
        return Promise.reject('每日签到固定奖励的积分和优惠券同时只能选择一项')
      }

      if (formModel.value.dayPointOpen) {
        if (!formModel.value.dayPointReward) {
          return Promise.reject('请输入 - 每日签到固定奖励 - 积分')
        }
      }

      if (formModel.value.dayCouponOpen) {
        if (!formModel.value.couponId) {
          return Promise.reject('请选择 - 每日签到固定奖励 - 优惠券')
        }
      }

      return Promise.resolve()
    }

    function validateContinuous() {
      if (formModel.value.signContinueRewardOpen) {
        if (!formModel.value.signContinueReward) {
          return Promise.reject('请输入 - 递增奖励 - 积分')
        }

        if (!formModel.value.signContinueRewardInvalidDays) {
          return Promise.reject('请输入 - 递增奖励 - 天数')
        }
      }

      if (formModel.value.assignDaysRewardOpen) {
        if (!formModel.value.assignDays) {
          return Promise.reject('请输入 - 指定天数奖励 - 天数')
        }

        if (
          formModel.value.assignDaysCouponOpen &&
          formModel.value.assignDaysPointOpen
        ) {
          return Promise.reject('指定天数奖励的积分和优惠券同时只能选择一项')
        }

        if (formModel.value.assignDaysCouponOpen) {
          if (!formModel.value.assignDaysCouponId) {
            return Promise.reject('请选择 - 指定天数奖励 - 优惠券')
          }
        }

        if (formModel.value.assignDaysPointOpen) {
          if (!formModel.value.assignDaysPointReward) {
            return Promise.reject('请输入 - 指定天数奖励 - 积分')
          }
        }
      }

      return Promise.resolve()
    }

    function handleCancel() {
      showConfirm({
        content: '确认取消？该操纵会重置表单数据！',
        onOk: () => {
          Object.assign(formModel.value, resetData.value)
        }
      })
    }

    async function handleSubmit() {
      try {
        loading.value = true
        await Promise.all([validateDay(), validateContinuous()])
        await marketingApi.updateSignInSetting(formModel.value)
        notification.success({
          message: '更新签到配置成功',
          duration: 1.5
        })
        Object.assign(resetData.value, formModel.value)
      } catch (error) {
        message.error(error as any, 2)
      } finally {
        loading.value = false
      }
    }

    async function init() {
      try {
        loading.value = true

        const list = await couponApi.getSimpleList({
          type: 1
        })
        couponOptions.value = list.map(v => ({ label: v.name, value: v.id }))

        const res = await marketingApi.getSignInSetting()

        // 当关联的优惠券被删除时需要置空
        const ids = couponOptions.value.map(v => v.value)

        if (!ids.includes(res.couponId)) {
          res.couponId = undefined as any
        }

        if (!ids.includes(res.assignDaysCouponId)) {
          res.assignDaysCouponId = undefined as any
        }

        Object.assign(formModel.value, res)
        Object.assign(resetData.value, res)
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      init()
    })

    return {
      loading,
      formModel,
      couponOptions,
      pointDisabled,
      couponDisabled,
      incrementDisabled,
      continuousDisabled,
      subPointDisabled,
      subCouponDisabled,
      handleCancel,
      handleSubmit
    }
  },
  render() {
    return (
      <div>
        <Spin spinning={this.loading}>
          <div class={styles.formSection}>
            <h3 class={styles.title}>每日签到固定奖励</h3>
            <Row align="middle">
              <Col span={2}>
                <Radio
                  v-model:checked={this.formModel.dayPointOpen}
                  onChange={value => {
                    if (value) {
                      this.formModel.dayCouponOpen = false
                    }
                  }}
                >
                  积分
                </Radio>
              </Col>
              <Col span={22}>
                <span>送</span>
                <Input
                  v-model:value={this.formModel.dayPointReward}
                  disabled={this.pointDisabled}
                  style={{ width: '100px', margin: '0 10px' }}
                />
                <span>积分</span>
              </Col>
            </Row>
            <Row class={styles.formRow} align="middle">
              <Col span={2}>
                <Radio
                  v-model:checked={this.formModel.dayCouponOpen}
                  onChange={value => {
                    if (value) {
                      this.formModel.dayPointOpen = false
                    }
                  }}
                >
                  优惠券
                </Radio>
              </Col>
              <Col span={22}>
                <Select
                  v-model:value={this.formModel.couponId}
                  placeholder="选择优惠券"
                  disabled={this.couponDisabled}
                  style={{ width: '300px' }}
                >
                  {this.couponOptions.map(v => (
                    <SelectOption value={v.value}>{v.label}</SelectOption>
                  ))}
                </Select>
              </Col>
            </Row>
          </div>
          <div class={styles.formSection}>
            <h3 class={styles.title}>连续签到额外奖励</h3>
            <Row>
              <Col span={2}>递增奖励</Col>
              <Col span={22}>
                <Row align="middle">
                  <Col span={24}>
                    <Switch
                      v-model:checked={this.formModel.signContinueRewardOpen}
                    />
                  </Col>
                </Row>
                <Row class={styles.formRowWrap} align="middle">
                  <Col span={1}>积分</Col>
                  <Col span={23}>
                    <span>第二天起递增奖励</span>
                    <Input
                      v-model:value={this.formModel.signContinueReward}
                      disabled={this.incrementDisabled}
                      style={{ width: '100px', margin: '0 10px' }}
                    />
                    <span>积分</span>
                    <Input
                      v-model:value={
                        this.formModel.signContinueRewardInvalidDays
                      }
                      v-slots={{
                        addonAfter: () => '天'
                      }}
                      disabled={this.incrementDisabled}
                      style={{ width: '100px', margin: '0 10px' }}
                    />
                    <span>后，不再递增</span>
                  </Col>
                </Row>
              </Col>
            </Row>
            <Row class={styles.formRow}>
              <Col span={2}>指定天数奖励</Col>
              <Col span={22}>
                <Row align="middle">
                  <Col span={24}>
                    <Switch
                      v-model:checked={this.formModel.assignDaysRewardOpen}
                    />
                  </Col>
                </Row>
                <div class={styles.formRowWrap}>
                  <Row class={styles.formRow} align="middle">
                    <Col span={24} style={{ display: 'flex' }}>
                      <span style={{ alignSelf: 'center' }}>连续签到第</span>
                      <Input
                        v-model:value={this.formModel.assignDays}
                        v-slots={{
                          addonAfter: () => '天'
                        }}
                        disabled={this.continuousDisabled}
                        style={{ width: '100px', margin: '0 10px' }}
                      />
                      <span style={{ alignSelf: 'center' }}>
                        额外赠送以下奖励
                      </span>
                    </Col>
                  </Row>
                  <Row class={styles.formRow} align="middle">
                    <Col span={24}>
                      <Radio
                        v-model:checked={this.formModel.assignDaysCouponOpen}
                        disabled={this.continuousDisabled}
                        style={{ marginRight: '20px' }}
                        onChange={value => {
                          if (value) {
                            this.formModel.assignDaysPointOpen = false
                          }
                        }}
                      >
                        优惠券
                      </Radio>
                      <Select
                        v-model:value={this.formModel.assignDaysCouponId}
                        placeholder="选择优惠券"
                        disabled={
                          this.continuousDisabled || this.subCouponDisabled
                        }
                        style={{ width: '300px' }}
                      >
                        {this.couponOptions.map(v => (
                          <SelectOption value={v.value}>{v.label}</SelectOption>
                        ))}
                      </Select>
                    </Col>
                  </Row>
                  <Row class={styles.formRow} align="middle">
                    <Col span={24}>
                      <Radio
                        v-model:checked={this.formModel.assignDaysPointOpen}
                        disabled={this.continuousDisabled}
                        style={{ marginRight: '32px' }}
                        onChange={value => {
                          if (value) {
                            this.formModel.assignDaysCouponOpen = false
                          }
                        }}
                      >
                        积分
                      </Radio>
                      <span>送</span>
                      <Input
                        v-model:value={this.formModel.assignDaysPointReward}
                        disabled={
                          this.continuousDisabled || this.subPointDisabled
                        }
                        style={{ width: '100px', margin: '0 10px' }}
                      />
                      <span>积分</span>
                    </Col>
                  </Row>
                </div>
              </Col>
            </Row>
          </div>
          <div class={styles.formSection}>
            <h3 class={styles.title}>引流配置</h3>
            <Row align="middle">
              <Col span={2}>上传模板图片</Col>
              <Col span={22}>
                <div style={{ display: 'flex' }}>
                  <UploadFile v-model={[this.formModel.signImage, 'urls']}>
                    上传图片
                  </UploadFile>
                  <span style={{ color: '#706f6f' }}>
                    请上传600x1080px或900x1080px图片，图片需要包含按钮
                  </span>
                </div>
              </Col>
            </Row>
            <Row class={styles.formRow} align="middle">
              <Col span={2}>跳转链接</Col>
              <Col span={22}>
                <RadioGroup v-model:value={this.formModel.signLinkType}>
                  <Radio value={1}>H5链接</Radio>
                  <Radio value={2}>小程序链接</Radio>
                </RadioGroup>
              </Col>
            </Row>
            {this.formModel.signLinkType === 1 && (
              <Row class={styles.formRow} align="middle">
                <Col span={2}>地址：</Col>
                <Col span={22}>
                  <Input
                    maxlength={300}
                    v-model:value={this.formModel.signWebUrl}
                    placeholder="请输入"
                    style={{ width: '200px' }}
                  />
                </Col>
              </Row>
            )}
            {this.formModel.signLinkType === 2 && (
              <div>
                <Row class={styles.formRow} align="middle">
                  <Col span={2}>小程序目录：</Col>
                  <Col span={22}>
                    <Input
                      maxlength={120}
                      v-model:value={this.formModel.signMiniappDirectory}
                      placeholder="请输入"
                      style={{ width: '200px' }}
                    />
                  </Col>
                </Row>
                <Row class={styles.formRow} align="middle">
                  <Col span={2}>原始ID：</Col>
                  <Col span={22}>
                    <Input
                      maxlength={60}
                      v-model:value={this.formModel.signMiniappUrl}
                      placeholder="请输入"
                      style={{ width: '200px' }}
                    />
                  </Col>
                </Row>
              </div>
            )}
          </div>
          <Divider />
          <div class={styles.formBtns}>
            <Space>
              <Button onClick={this.handleCancel}>取消</Button>
              <Button type="primary" onClick={this.handleSubmit}>
                确定
              </Button>
            </Space>
          </div>
        </Spin>
      </div>
    )
  }
})
